import store from '@/store'
import _ from 'lodash'
import { request } from '../common/util'

/**
 * 直接设置model值
 *
 * 执行方式:
 *    modelSet('state.userInfo.name','vue') 调用store/index.js中modelSet
 *    modelSet('app.userInfo.name','vue') 调用store/modules/---.js中modelSet
 *
 * @param path
 * @param data
 */
export function modelSet(path, data){
  let [moduleName, ...modulePath] = path.split(/\./)
  return store.commit(`modelSet`, { path: path, data }) // 通过index.js中modelSet可以获取全部
}

export function modelAssign(path, data){
  let [moduleName, ...modulePath] = path.split(/\./)
  return store.commit(`modelAssign`, { path: path, data }) // 通过index.js中modelSet可以获取全部
}

export function modelGet(path){
  return _.get(store.state, path)
}

export async function modelSetWithServer(path, option){
  let [moduleName, ...modulePath] = path.split(/\./)
  try {
    let res = await request(option)
    if (path) {
      await modelSet(path, res)
    }
    return res
  } catch (e) {
    return Promise.reject(e)
  }
}

/**
 * 设置
 * @param p0
 * @param p1
 * @param p2
 * @returns {Promise<*>}
 */
export async function modelSetWithServer2(p0, p1, p2){
  let moduleName = p0
  let path = p1
  let data = p2

  if (/\./.test(p0)) {
    let moduleNameArr = p0.split('.')
    moduleName = moduleNameArr.shift()
    path = moduleNameArr.join('.')
    data = p1
  }

  try {
    let res = await store.dispatch(`${moduleName}/modelSetWithServer`, { path, data })
    return res
  } catch (e) {
    return Promise.reject(e)
  }
}
